package example.demo.jdbcTemUse;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.transaction.support.DefaultTransactionStatus;

import javax.sql.DataSource;
import java.sql.Connection;

@Slf4j
@Component
public class JdbcTempBean {

    /*
        @Configuration(proxyBeanMethods = false)
            @ConditionalOnMissingBean(JdbcOperations.class)
            class JdbcTemplateConfiguration {
            .....

     */
//    @Bean
//    JdbcTemplate jdbcTemplate(DataSource dataSource) {
//        return new JdbcTemplate(dataSource);
//    }
    @Autowired
    JdbcTemplate jdbcTemplate;

    @SuppressWarnings("all")
//    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void updateStock() {
//        log.info(Thread.currentThread().getName() + "=====JdbcTempBean====updateStock");

//        TransactionStatus transactionStatus = TransactionAspectSupport.currentTransactionStatus();
//        if (transactionStatus instanceof DefaultTransactionStatus) {
//            DefaultTransactionStatus status = (DefaultTransactionStatus) transactionStatus;
//            Object transaction = status.getTransaction();
//        }
        // todo 借助数据库完成秒杀。
        //                                                                                            0           1                     2
        //update kill_goods set seckill_stock = seckill_stock - ? where id = ? and seckill_stock >= ? 不能等于
        int update = jdbcTemplate.update("update kill_goods set seckill_stock = seckill_stock - ? where id = ? and seckill_stock > ?", 1, 10, 0);

        if (update == 0) {
            log.info(Thread.currentThread().getName() + "-----抢购失败");
        } else {
            log.info(Thread.currentThread().getName() + "------抢购-succeed");
        }
    }
}
